<template>
  <a-modal
    :open="open"
    title="批量导入态势对象"
    width="700px"
    :confirmLoading="loading"
    @ok="handleImport"
    @cancel="handleCancel"
  >
    <a-space direction="vertical" style="width: 100%" :size="16">
      <!-- 格式选择 -->
      <div>
        <div class="label">导入格式</div>
        <a-radio-group v-model:value="importFormat">
          <a-radio-button value="json">JSON</a-radio-button>
          <a-radio-button value="csv">CSV</a-radio-button>
          <a-radio-button value="xml">XML</a-radio-button>
          <a-radio-button value="yaml">YAML</a-radio-button>
        </a-radio-group>
      </div>

      <!-- 文件上传 -->
      <div>
        <div class="label">选择文件</div>
        <a-upload
          :before-upload="handleFileUpload"
          :file-list="fileList"
          @remove="handleFileRemove"
          :accept="getFileAcceptTypes()"
        >
          <a-button>
            <upload-outlined />
            选择文件
          </a-button>
        </a-upload>
      </div>

      <!-- 文件内容预览 -->
      <div v-if="fileContent">
        <div class="label">文件内容预览</div>
        <a-textarea
          v-model:value="fileContent"
          :rows="10"
          placeholder="文件内容将在这里显示"
          style="font-family: monospace"
        />
      </div>

      <!-- 导入结果 -->
      <div v-if="importResult">
        <a-alert
          :message="`导入完成: 成功 ${importResult.success_count} 条，失败 ${importResult.error_count} 条`"
          :type="importResult.error_count > 0 ? 'warning' : 'success'"
          show-icon
        />

        <!-- 错误详情 -->
        <div v-if="importResult.errors && importResult.errors.length > 0" style="margin-top: 12px">
          <a-collapse>
            <a-collapse-panel key="errors" header="查看错误详情">
              <div v-for="(error, index) in importResult.errors" :key="index" class="error-item">
                <div><strong>行 {{ error.index + 1 }}:</strong> {{ error.error }}</div>
                <pre>{{ JSON.stringify(error.data, null, 2) }}</pre>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>

      <!-- 帮助说明 -->
      <a-collapse>
        <a-collapse-panel key="help" header="导入格式说明">
          <div class="help-content">
            <h4>JSON 格式示例：</h4>
            <pre>{{ jsonExample }}</pre>

            <h4 style="margin-top: 16px">CSV 格式示例：</h4>
            <pre>{{ csvExample }}</pre>

            <h4 style="margin-top: 16px">XML 格式示例：</h4>
            <pre>{{ xmlExample }}</pre>

            <h4 style="margin-top: 16px">YAML 格式示例：</h4>
            <pre>{{ yamlExample }}</pre>

            <a-alert
              message="提示"
              description="JSON/XML/YAML 格式支持完整的字段结构；CSV 格式支持基础字段，扩展字段需使用 JSON 字符串表示"
              type="info"
              style="margin-top: 12px"
            />
          </div>
        </a-collapse-panel>
      </a-collapse>
    </a-space>
  </a-modal>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { importSituationData } from '@/apis'

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:open', 'success'])

const loading = ref(false)
const importFormat = ref('json')
const fileContent = ref('')
const fileList = ref([])
const importResult = ref(null)

const jsonExample = `[
  {
    "object_type": "weapon",
    "name": "东风-21导弹",
    "code": "DF-21",
    "model": "DF-21D",
    "organization": "火箭军",
    "deployment_status": "已部署",
    "type_specific_data": {
      "weapon_category": "导弹",
      "range": 2000.0,
      "warhead_type": "常规"
    },
    "tags": ["中程", "弹道导弹"]
  }
]`

const csvExample = `object_type,name,code,model,organization,deployment_status
weapon,东风-21导弹,DF-21,DF-21D,火箭军,已部署
infrastructure,首都机场,PEK-01,国际机场,民航局,已部署`

const xmlExample = `<?xml version="1.0" encoding="UTF-8"?>
<situation_objects>
  <situation_object>
    <object_type>weapon</object_type>
    <name>东风-21导弹</name>
    <code>DF-21</code>
    <model>DF-21D</model>
    <organization>火箭军</organization>
    <deployment_status>已部署</deployment_status>
    <type_specific_data>
      <weapon_category>导弹</weapon_category>
      <range>2000.0</range>
      <warhead_type>常规</warhead_type>
    </type_specific_data>
    <tags>
      <item>中程</item>
      <item>弹道导弹</item>
    </tags>
  </situation_object>
</situation_objects>`

const yamlExample = `situation_objects:
  - object_type: weapon
    name: 东风-21导弹
    code: DF-21
    model: DF-21D
    organization: 火箭军
    deployment_status: 已部署
    type_specific_data:
      weapon_category: 导弹
      range: 2000.0
      warhead_type: 常规
    tags:
      - 中程
      - 弹道导弹`

// 文件上传处理
function handleFileUpload(file) {
  const reader = new FileReader()

  reader.onload = (e) => {
    fileContent.value = e.target.result
    fileList.value = [file]
  }

  reader.readAsText(file)

  // 阻止默认上传行为
  return false
}

// 移除文件
function handleFileRemove() {
  fileContent.value = ''
  fileList.value = []
  importResult.value = null
}

// 执行导入
async function handleImport() {
  if (!fileContent.value) {
    message.warning('请先选择文件')
    return
  }

  loading.value = true
  importResult.value = null

  try {
    const response = await importSituationData(importFormat.value, fileContent.value)
    importResult.value = response.result

    if (response.result.error_count === 0) {
      message.success(`导入成功！共导入 ${response.result.success_count} 条数据`)
      emit('success')

      // 延迟关闭弹窗
      setTimeout(() => {
        handleCancel()
      }, 1500)
    } else {
      message.warning(`导入完成，成功 ${response.result.success_count} 条，失败 ${response.result.error_count} 条`)
    }
  } catch (error) {
    message.error('导入失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取文件接受类型
function getFileAcceptTypes() {
  switch (importFormat.value) {
    case 'json':
      return '.json'
    case 'csv':
      return '.csv'
    case 'xml':
      return '.xml'
    case 'yaml':
      return '.yaml,.yml'
    default:
      return '.json,.csv,.xml,.yaml,.yml'
  }
}

// 取消
function handleCancel() {
  emit('update:open', false)

  // 重置状态
  setTimeout(() => {
    importFormat.value = 'json'
    fileContent.value = ''
    fileList.value = []
    importResult.value = null
  }, 300)
}
</script>

<style scoped>
.label {
  font-weight: 500;
  margin-bottom: 8px;
}

.help-content h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.help-content pre {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  margin: 8px 0 0 0;
}

.error-item {
  padding: 8px;
  margin-bottom: 8px;
  background: #fff2e8;
  border-left: 3px solid #ff7a00;
  border-radius: 2px;
}

.error-item pre {
  background: #fff;
  padding: 8px;
  border-radius: 4px;
  margin-top: 8px;
  font-size: 12px;
  overflow-x: auto;
}
</style>
